package com.example.java.escape.thread;

import java.util.concurrent.ThreadLocalRandom;

/**
 * @author : weicai
 * @date : 17:21 2020/11/28
 *
 *ThreadLocal 使用示例
 */
public class CSGameByThreadLocal {

    private static final Integer BULLET_NUMBER = 1500;
    public static final Integer KILLED_ENEMIES = 0;
    public static final Integer LIFE_VALUE = 10;
    public static final Integer TOTAL_PLAYERS = 10;

    //随机数用来展示每个对象的不同的数据
    public static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();

    // 初始化子弹数
    public static final ThreadLocal<Integer> BULLET_NUMBER_THREAD_LOCAL = ThreadLocal.withInitial(() -> BULLET_NUMBER);
    // 初始化杀敌数
    public static final ThreadLocal<Integer> KILLED_ENEMIES_THREAD_LOCAL = ThreadLocal.withInitial(() -> KILLED_ENEMIES);
    // 初始化生命数
    public static final ThreadLocal<Integer> LIFE_VALUE_THREAD_LOCAL = ThreadLocal.withInitial(() -> LIFE_VALUE);

    //定义每位队员
    private static class Player extends Thread {
        @Override
        public void run() {
            Integer bullets = BULLET_NUMBER_THREAD_LOCAL.get() - RANDOM.nextInt(BULLET_NUMBER);
            Integer killedEnemies = KILLED_ENEMIES_THREAD_LOCAL.get() - RANDOM.nextInt(TOTAL_PLAYERS / 6);
            Integer lifeValue = LIFE_VALUE_THREAD_LOCAL.get() - RANDOM.nextInt(LIFE_VALUE);

            System.out.println(getName() + "子弹数有：" + bullets);
            System.out.println(getName() + "杀敌数：" + killedEnemies);
            System.out.println(getName() + "剩余生命：" + lifeValue + "\n");

            BULLET_NUMBER_THREAD_LOCAL.remove();
            KILLED_ENEMIES_THREAD_LOCAL.remove();
            LIFE_VALUE_THREAD_LOCAL.remove();
        }

        public static void main(String[] args) {
            for (int i = 0; i< TOTAL_PLAYERS; i++) {
                new Player().start();
            }
        }
    }



}
